package entities;

import java.util.ArrayList;
import java.util.StringTokenizer;

public class Rule 
{
	private ArrayList<Integer> antecedents;
	private int consequent;
	
	private static final String RULE_SEPERATOR = "->";
	
	public Rule(ArrayList<Integer> a, int c) 
	{		
		antecedents = new ArrayList<Integer>(a);
		consequent = c;
	}
	
	public static Rule GenerateRule(String ruleLine)
	{
		ArrayList<Integer> antecedents = new ArrayList<Integer>();
		int consequent = -1;
		
		StringTokenizer tokenizer = new StringTokenizer(ruleLine, " ");
		boolean storingAntecedents = true;
		while(tokenizer.hasMoreTokens())
		{
			String token = tokenizer.nextToken();
			if(storingAntecedents && token.equals(RULE_SEPERATOR))
				storingAntecedents = false;
			else if(storingAntecedents)
				antecedents.add(Integer.parseInt(token));
			else if(!storingAntecedents && consequent == -1)
				consequent = Integer.parseInt(token);
		}
		
		if(antecedents.size() > 0)
			return new Rule(antecedents, consequent);
		else		
			return null;
	}
	
	public ArrayList<Integer> getAntecedents()
	{
		return antecedents;
	}
	
	public Integer getConsequent()
	{
		return consequent;
	}
	
	public String toString()
	{
		StringBuilder outputSB = new StringBuilder();
		
		for(int i = 0; i < antecedents.size(); i++) 
		{			
			outputSB.append(antecedents.get(i));
			outputSB.append(" ");
		}
		outputSB.append("-> ");
		outputSB.append(consequent);
		
		return outputSB.toString();
	}
	
	public boolean containsAntecedant(int productId)
	{
		boolean contains = false;
		for(int i = 0; i < antecedents.size(); i++)
		{
			if(antecedents.get(i) == productId)
			{
				contains = true;
				break;
			}
		}
		return contains;
	}
}
